using UnityEngine;

namespace GameToolkit
{
    [RequireComponent(typeof(CharacterController))]
    public class DefaultCharacterPoseture : MonoBehaviour, ActorBehaviour.IDefaultPoseture
    {
        CharacterController mCtrl;
        int ActorBehaviour.IDefaultPoseture.ExecutionOrder => 0;

        ActorBehaviour.EPosture mPoseture;
        Vector3 mVelocity;
        public ActorBehaviour.EPosture PosetureState
        {
            get { return mPoseture; }
            private set
            {
                if(mPoseture != value)
                {
                    mPoseture = value;
                }
            }
        }

        public Vector3 Velocity => mVelocity;

        public void OnEnter(Vector3 initVelocity, ActorBehaviour.EPosture initPoseture)
        {
            mVelocity = initVelocity;
            PosetureState = initPoseture;
        }

        public void OnExit()
        {
        }

        public void OnFeatureEnable(ActorBehaviour actor)
        {
            PosetureState = ActorBehaviour.EPosture.Standing;
            if (mCtrl == null)
                mCtrl = actor.GetComponent<CharacterController>();
        }

        public void OnFeatureDisable(ActorBehaviour actor)
        {
        }

        public void OnUpdatePoseture(float deltaTime)
        {
            if(mCtrl != null)
            {
                var v = Physics.gravity * deltaTime + mVelocity;
                var mov = (v + mVelocity) * deltaTime * 0.5f;
                var collision = mCtrl.Move(mov);
                if(mCtrl.isGrounded)
                {
                    mVelocity = Vector3.zero;
                    PosetureState = ActorBehaviour.EPosture.Standing;
                }
                else
                {
                    mVelocity = v;
                    PosetureState = ActorBehaviour.EPosture.Falling;
                }
            }
        }
    }
}
